/*
 *  class_dump.c
 *
 *  Copyright (C) 2011  Jason<linux8192@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

#include "debug.h"
#include "classfile.h"
#include "constant_info.h"

#define FILE_SIZE	(1024 * 4096)

static char	*class_file_buffer;
static int	file_len;

void print_usage()
{
	printf("\n\nUsage: classdump xxx.class\n\n");
}

int alloc_file_buffer()
{
	class_file_buffer = malloc(FILE_SIZE);
	if (!class_file_buffer) {
		LOGE("Allocate buffer failed.");
		return -1;
	}
	return 0;
}

int open_file(char *filename)
{
	int	fd = -1;

	fd = open(filename, O_RDONLY);
	if (fd == 0) {
		perror("Open file failed");
		return -1;
	}

	if (alloc_file_buffer()) {
		return -2;
	}

	if ((file_len = read(fd, class_file_buffer, FILE_SIZE)) <= 0) {
		perror("Read file failed");
		return -3;
	}

	//LOGV("file length = %d\n", file_len);

	return 0;
}

int main(int argc, char *argv[])
{
	if (argc != 2) {
		print_usage();
		return -1;
	}

	if (open_file(argv[1])) {
		return -1;
	}

	dump_class(parse_class_descriptor(class_file_buffer, file_len));

	return 0;
}
